// useBasketDrag.js
/**
* @description:竖直方向拖拽元素
* @param {document} 要拖拽的dom的父dom
* @param {dragSection} 要拖拽的dom
* @returns {}
*/

export default function useBasketDrag(basketWrapper, dragSection) {
    let move = () => { };
    let mouseup = () => { };
    let touchend = () => { };

    const startDragging = (event) => {
        const eventHandler = (event) => {
            let originalY = 0;
            if (event instanceof MouseEvent) {
                originalY = event.clientY;
            }

            if (event instanceof TouchEvent) {
                originalY = event.targetTouches[0].clientY;
            }

            const innerHeight = window.innerHeight;
            const elementY = parseInt(getComputedStyle(basketWrapper).top) || 0;
            const rootHeight = basketWrapper.offsetHeight;

            move = (moveEvent) => {
                moveEvent.preventDefault();
                let clientY = 0;

                if (moveEvent instanceof MouseEvent) {
                    clientY = moveEvent.clientY;
                }

                if (moveEvent instanceof TouchEvent) {
                    clientY = moveEvent.targetTouches[0].clientY;
                }

                const rangeHeight = innerHeight - rootHeight;
                const newY = elementY + clientY - originalY;

                if (newY >= 0 && newY <= rangeHeight) {
                    basketWrapper.style.top = newY + 'px';
                }
            };

            document.addEventListener('mousemove', move);
            document.addEventListener('touchmove', move);

        };

        // dragSection.addEventListener('touchstart', eventHandler);

        mouseup = () => {
            console.log('mouseup1')
            document.removeEventListener('mousemove', move
            );
            document.removeEventListener('touchmove', move);
        };

        touchend = () => {
            console.log('touchend1')
            document.removeEventListener('mousemove', move);
            document.removeEventListener('touchmove', move);
        };
        dragSection.addEventListener('mousedown', eventHandler);
        dragSection.addEventListener('touchstart', eventHandler);
        document.addEventListener('mouseup', mouseup);

        document.addEventListener('touchend', touchend);
    };

    const stopDragging = () => {
        document.removeEventListener('mouseup', mouseup);
        document.removeEventListener('touchend', touchend);
    };

    return { startDragging, stopDragging };
}
